<?php

namespace CMS;

class Min {
	private $css;
	private $js;

	protected $tmp;

	public $static_css;
	public $static_js;

	public function __construct() {
		$this->tmp = ROOT . DS . 'tmp' . DS;
		$this->check();
	}

	private function prio($a, $b) {
		$info_a = pathinfo($a);
		$info_b = pathinfo($b);

		return strnatcmp($info_a['basename'], $info_b['basename']);
	}

	private function getFiles() {
		$this->css = Helper::find_all_files(ROOT . DS . 'pub' . DS . 'css', 'css');
		$this->js = Helper::find_all_files(ROOT . DS . 'pub' . DS . 'js', 'js');

		usort($this->css, array('CMS\Min', 'prio'));
		usort($this->js, array('CMS\Min', 'prio'));
	}

	private function check() {
		$this->getFiles();
		$this->getCss();
		$this->getJs();
	}

	private function identCss() {
		$time = null;
		foreach($this->css as $css)
			$time .= filemtime($css);

		return $time;
	}

	private function identJs() {
		$time = null;
		foreach($this->js as $js)
			$time .= filemtime($js);

		return $time;
	}

	private function getCss() {
		if(!is_file($this->tmp . 'static.css.cache'))
			return $this->rebuildCss();

		if(file_get_contents($this->tmp . 'static.css.cache') === $this->identCss())
			return $this->staticCss();

		return $this->rebuildCss();
	}

	private function getJs() {
		if(!is_file($this->tmp . 'static.js.cache'))
			return $this->rebuildJs();

		if(file_get_contents($this->tmp . 'static.js.cache') === $this->identJs())
			return $this->staticJs();

		return $this->rebuildJs();
	}

	private function rebuildCss() {
		$out = null;
		foreach($this->css as $css)
			$out .= file_get_contents($css);

		file_put_contents($this->tmp . 'static.css', ENV == 1 ? \Minify_CSS::minify($out) : $out);
		file_put_contents($this->tmp . 'static.css.cache', $this->identCss());

		$this->staticCss();
	}

	private function rebuildJs() {
		$out = null;
		foreach($this->js as $js)
			$out .= file_get_contents($js);

		file_put_contents($this->tmp . 'static.js', ENV == 1 ? \Minify_JS_ClosureCompiler::minify($out) : $out);
		file_put_contents($this->tmp . 'static.js.cache', $this->identJs());

		$this->staticJs();
	}

	private function staticCss() {
		if(!is_file($this->tmp . 'static.css'))
			return $this->rebuildCss();

		$this->static_css = "css/static.css?_=" . filemtime($this->tmp . 'static.css');
	}

	private function staticJs() {
		if(!is_file($this->tmp . 'static.js'))
			return $this->rebuildJs();

		$this->static_js = "js/static.js?_=" . filemtime($this->tmp . 'static.js');
	}
}